<template>
  <div class="elm-edit">
    <elm-page-bb>
      <el-form ref="model" :model="model" size="small" label-width="120px">
        <elm-row>
          <el-form-item label="销售批次" prop="name" :rules="input_rule">
            <el-input v-model="model.name" ></el-input>
          </el-form-item>
          <el-form-item label="货物名称" prop="dict" :rules="input_rule">
            <elm-select style="width: 100%" v-model="model.dict" url="/business/jxc/goods/dict/GetData"></elm-select>
          </el-form-item>
        </elm-row>
        <elm-row>
          <el-form-item label="销售价格" prop="price" :rules="[{trigger: 'blur' ,validator: validateNumber}]">
            <el-input v-model.number="model.price"></el-input>
          </el-form-item>
          <el-form-item label="税率" prop="tex" :rules="[{trigger: 'blur' ,validator: validateNumber}]">
            <el-input v-model.number="model.tex">
              <template slot="append">
                <div style="width: 25px;text-align: center;">{{"%"}}</div>
              </template>
            </el-input>
          </el-form-item>
        </elm-row>
        <elm-row>
          <el-form-item label="出库时间" prop="out_time">
            <el-date-picker v-model="model.out_time"  type="datetime" value-format="yyyy-MM-dd HH-mm-ss" style="width: 100%"></el-date-picker>
          </el-form-item>
          <el-form-item label="出库员" prop="out_role">
            <elm-ei v-model="model.out_person"></elm-ei>
          </el-form-item>
        </elm-row>
        <el-form-item label="销售详情" :key="model.dict" v-if="model.dict">
          <el-row>
            <span style="margin: 0 10px">{{"销售总数:"}}</span>
            <el-input v-model.number="model.quantity" :key="model.unit" size="mini" style="width: 300px" disabled>
              <template slot="append" v-if="model.unit"><div style="width: 25px;text-align: center;">{{model.unit}}</div></template>
            </el-input>
            <right>
              <el-button-group>
                <el-button size="mini" @click="addOutData">新增</el-button>
              </el-button-group>
            </right>
          </el-row>
          <elm-table ref="table" :data="outData" :page-size="9999" style="height: 30vh" :show-index="false">
            <el-table-column prop="goods_id" label="进货批次" align="center" header-align="center" width="120">
              <template v-slot="scope">
                <el-select v-model="outData[scope.$index].goods_id" style="width:100%" @change="loadOutData(scope.$index,outData[scope.$index].goods_id)" filterable>
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="specification" label="规格/型号" align="center" header-align="center" width="90"></el-table-column>
            <el-table-column prop="unit" label="单位" align="center" header-align="center" width="50"></el-table-column>
            <el-table-column prop="price" label="进货价格" align="right" header-align="center"></el-table-column>
            <el-table-column prop="tex" label="税率" align="center" header-align="center">
              <template v-slot="scope">
                {{scope.row.tex?scope.row.tex+"%":""}}
              </template>
            </el-table-column>
            <el-table-column prop="manufacturer" label="厂家" align="left" header-align="center" min-width="100"></el-table-column>
            <el-table-column prop="made_date" label="生产日期" align="center" width="120" :formatter="formatDate"></el-table-column>
            <el-table-column prop="shelf_life" label="保质期至" align="center" width="120" :formatter="formatDate"></el-table-column>
            <el-table-column prop="remarks" label="备注" align="center" header-align="center"></el-table-column>
            <el-table-column prop="quantity" label="库存数量" align="right" header-align="center"></el-table-column>
            <el-table-column prop="out_quantity" label="销售数量" fixed="right" align="right" header-align="center">
              <template v-slot="scope">
                <el-input v-model.number="outData[scope.$index].out_quantity" style="width:100%" @blur="getQuantity(scope.$index)" v-if="outData[scope.$index].goods_id"></el-input>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="50px" align="center">
              <template v-slot="scope">
                <el-button  type="text" size="mini" @click="deleteOutData(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </elm-table>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="model.remarks" type="textarea" :rows="2"></el-input>
        </el-form-item>
      </el-form>
      <template #bottom>
        <el-button type="success" size="small" @click="save">保存并继续</el-button>
        <el-button type="success" size="small" @click="submit">立即保存</el-button>
        <el-button size="small" @click="close">取消</el-button>
      </template>
    </elm-page-bb>
  </div>
</template>

<script>
export default {
  extends: elmVueBase,
  data() {
    return {
      model: {
        id: elm.newGuid(),
        dict:null,
        out_person:null,
        unit:null,
        quantity:0,
        is_disuse:0
      },
      resData:{
        quantity:null,
      },
      outData:[],
      ruleEnable:false,
      options:[]
    }
  },
  async created() {
    this.model.out_time=this.get_time();
    this.model.out_person=await this.get_user_ei();
  },
  destroyed() {
    this.request.callVue.tablebinding();
  },
  computed:{
    input_rule(){
      if(this.ruleEnable)
        return [{ required: true, message: '必须填写'}];
      else
        return [];
    },
  },
  methods: {
    async save() {
      var res = await this.upload();
      if (res) {
        this.v('保存成功,请继续。')
        this.ruleEnable=false;
        this.model={
          id:elm.newGuid(),
          name:this.model.name,
          out_time:this.model.out_time,
          out_person:this.model.out_person,
          remarks:this.model.remarks,
          is_disuse:0
        }
      }
      else {
        this.error('保存失败，请稍后尝试。');
      }
    },
    async submit() {
      var res = await this.upload();
      if (res) {
        this.v('保存成功。')
        this.close();
        this.request.callVue.tablebinding();
      }
      else {
        this.error('保存失败，请稍后尝试。');
      }
    },
    get_time(){
      var now=new Date();
      return now.getFullYear() + '-'
          + (now.getMonth() + 1).toString().padStart(2, '0') + '-'
          + now.getDate().toString().padStart(2, '0')+ ' '
          + now.getHours().toString().padStart(2, '0') + ':'
          + now.getMinutes().toString().padStart(2, '0') + ':'
          + now.getSeconds().toString().padStart(2, '0');
    },
    async get_user_ei(){
      var res = await elm.post('/system/login/GetUserEi');
      if(res.length>0)
        return res[0].emp_code;
      else
        return "";
    },
    async getResData(Val){
      var res=await elm.post('/business/jxc/goods/dict/GetData',{id:Val});
      if(Val!=null&&Val!=""&&res.pagedata.length>0){
        this.resData=res.pagedata[0];
      }
    },
    async upload(){
      this.ruleEnable=true;
      await this.getResData(this.model.dict);
      await this.$refs["model"].validate();
      this.model.create_time = this.get_time();
      this.model.create_person = await this.get_user_ei();
      var res = await elm.post('/business/jxc/goods/out/Upsert', this.model);
      this.resData.quantity-=Number(this.model.quantity);
      var re = await elm.post('/business/jxc/goods/dict/Upsert', this.resData);
      for(var i in this.outData){
        var goodsData={id:this.outData[i].goods_id,...((({ id, ...rest }) => rest)(this.outData[i]))};
        var outResData={quantity:this.outData[i].out_quantity,...((({ quantity, ...rest }) => rest)(this.outData[i]))};
        goodsData.last_update_time=this.get_time();
        outResData.create_time=this.get_time();
        goodsData.quantity-=Number(this.outData[i].out_quantity);
        if(goodsData.quantity==0)
          await elm.post('/business/jxc/goods/Delete', goodsData);
        else
          await elm.post('/business/jxc/goods/Upsert', goodsData);
        await elm.post('/business/jxc/goods/out/stage/Upsert', outResData);
      }
      return (res==true && re ==true);
    },
    addOutData(){
      this.outData.push({out_id:this.model.id,id:elm.newGuid()});
    },
    deleteOutData(index){
      this.outData.splice(index,1);
    },
    async loadOutData(index,newId){
      var res = await elm.post('/business/jxc/goods/GetData',{id:newId});
      var item={...this.outData[index]};
      if(res.pagedata.length>0){
        Object.assign(item, (({ id, ...rest }) => rest)(res.pagedata[0]));
        this.$set(this.outData,index,{...item})
      }
    },
    getQuantity(index){
      if(this.outData[index].out_quantity<0)
        this.outData[index].out_quantity=0;
      if(this.outData[index].out_quantity>this.outData[index].quantity)
        this.outData[index].out_quantity=this.outData[index].quantity;
      this.model.quantity=0;
      for(var item in this.outData){
        this.model.quantity+=Number(this.outData[item].out_quantity||0);
      }
    }
  },
  watch: {
    'model.dict': async function (newVal) {
      var res = await elm.post('/business/jxc/goods/dict/GetGoodsData', {id: newVal});
      if (res.length > 0) {
        Object.assign(this.model, res[0]);
      }
      this.outData=[];
      this.options=await elm.post('/business/jxc/goods/GetOptions', {dict: newVal});
      await this.getResData(newVal);
    },
  }
}
</script>